package com.arelikebrothers.demo.concurrent.jdk;

import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by lennon on 01/05/2017.
 */
public class InterruptiblyLock implements Runnable {
    int lock;

    public static ReentrantLock lock1 = new ReentrantLock();
    public static ReentrantLock lock2 = new ReentrantLock();

    public InterruptiblyLock(int lock) {
        this.lock = lock;
    }

    @Override
    public void run() {

        try {
            if (lock == 1) {
                lock1.lockInterruptibly();
                Thread.sleep(500);
                lock2.lockInterruptibly();
            } else {
                lock2.lockInterruptibly();
                Thread.sleep(500);
                lock1.lockInterruptibly();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (lock1.isHeldByCurrentThread()) {
                lock1.unlock();
            }

            if (lock2.isHeldByCurrentThread()) {
                lock2.unlock();
            }
        }
    }


    public static void main(String[] args) {
        InterruptiblyLock r1 = new InterruptiblyLock(1);
        InterruptiblyLock r2 = new InterruptiblyLock(2);

        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r2);

        t1.start();
        t2.start();

        // 化解死锁
        t1.interrupt();
    }
}
